package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
)

func main() {
	//测试通过redigo连接redis
	conn, err := redis.Dial("tcp", "localhost:6379")
	defer conn.Close()
	if err != nil {
		fmt.Println("connect redis error :", err)
		return
	}
	fmt.Println("connect redis success")
	fmt.Println("----------------------------------------------------")
	//设置字符串
	ret, err := conn.Do("SET", "key1", "val1")
	fmt.Println(ret)
	//获取字符串
	ret, err = conn.Do("GET", "key1")
	retStr, err := redis.String(ret, err)
	fmt.Println(retStr, err)
	fmt.Println("----------------------------------------------------")

	//批量设置字符串
	ret, err = conn.Do("MSET", "key1", "val1", "key2", "val2")
	fmt.Println(ret)
	//批量获取字符串
	ret, err = conn.Do("MGET", "key1", "key2")
	retStrs, err := redis.Strings(ret, err)
	fmt.Println(retStrs, err)
	fmt.Println("----------------------------------------------------")
	//hash操作
	ret, err = conn.Do("HSET", "hash1", "k1", "v1")
	ret, err = conn.Do("HSET", "hash1", "k2", "v2")

	ret, err = conn.Do("HGET", "hash1", "k1")
	retStr, err = redis.String(ret, err)
	fmt.Println(retStr)
	ret, err = conn.Do("HGET", "hash1", "k2")
	retStr, err = redis.String(ret, err)
	fmt.Println(retStr)
	ret, err = conn.Do("HGETALL", "hash1")
	retStr, err = redis.String(ret, err)
	fmt.Println(retStr)
	fmt.Println("----------------------------------------------------")
	//queue操作，添加两个字符串1个数字
	_, err = conn.Do("rpush", "queue1", "aa", "bb", 12)
	//队列长度
	ret, err = conn.Do("llen", "queue1")
	fmt.Println("len:", ret)
	//不断从队列取出元素，打印字符串或数字格式
	for i := 0; i < 3; i++ {
		ret, err = conn.Do("lpop", "queue1")
		retStr, err = redis.String(ret, err)
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(retStr)
		}

		retInt, err := redis.Int(ret, err)
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(retInt)
		}
	}

	fmt.Println("------------------------------------------")
	//设置过期时间 5秒
	conn.Do("expire", "key1", 5)
	ret, err = conn.Do("get", "key1")
	fmt.Println(redis.String(ret, err))
	time.Sleep(5 * time.Second)
	ret, err = conn.Do("get", "key1")
	fmt.Println(redis.String(ret, err))
}
